#!/usr/bin/env python
# coding=utf-8

import requests
# from bs4 import BeautifulSoup
import json
import re
import os
# 'ascii' codec can't encode characters
import sys
reload(sys)
sys.setdefaultencoding('utf-8')

from BaiduMusicUtils import MusicDownload

class BaiduMusicDownload(object):

    def __init__(self):
        self.__BASE_URL = r'http://music.baidu.com/album/{album_id}'
        self.__SONG_DATA_URL = r'http://music.baidu.com/data/music/fmlink?songIds='
        self.__SONG_SEARCH_URL = None
        self.__SONG_REAL_DATA = None
        self.__SONG_REAL_URL = None 

        # Song info
        self.__SONG_ID = None
        self.__SONG_NAME = None
        self.__SONG_AUTHOR = None
        self.__SONG_FORMAT = None
        self.__SONG_ALBUM = None

    def get_song_id(self, album_id):
        self.__SONG_SEARCH_URL = self.__BASE_URL.format(album_id=album_id)

        req = requests.get(self.__SONG_SEARCH_URL)
        song = req.content

        song_id_all = re.findall(r'<a href="/song/([^"]+)"', str(song))

        if len(song_id_all) == 0:
            return False
        
        self.__SONG_ID = song_id_all
        return song_id_all

    def download_song(self, album_id):
        if not os.path.exists(album_id):
            os.mkdir(album_id)
        os.chdir(album_id)
        
        Music = MusicDownload()

        start = 0
        album_name = None
        while start < 40:
            self.get_song_id(album_id)
            for song_id in self.__SONG_ID:
                album_name = Music.download_song(song_id)
            start += 20

        os.chdir('..')
        os.system('mv {album_id} {album}'.format(album_id=album_id, 
                                        album=album_name.replace(' ', '-')))

if __name__ == '__main__':
    import sys
    
    if len(sys.argv) == 1:
        print "Usage:"
        print "\t{filename} Artist".format(filename=sys.argv[0])
        print "\t{filename} Artist1 Artist2 ...".format(filename=sys.argv[0])
        exit(False)

    download = BaiduMusicDownload()
    for song in sys.argv:
        if song == sys.argv[0]:
            continue
        download.download_song(song)
